import axios from 'axios'
import { Notify } from 'vant'
import router from '@/router'

// eslint-disable-next-line no-undef
console.log(BASE_URL, '------------BASE_URL----------------------')

const instance = axios.create({
  // eslint-disable-next-line no-undef
  baseURL: `${BASE_URL}`,
  timeout: 10000,
})

instance.interceptors.request.use(config=>{
  if (config.method === 'get') {
      if (!config.params) {
        config.params = {}
      }
      config.params.timestamp = new Date().getTime()
    }
    return config
  },err =>{
    return Promise.reject(err)
})

instance.interceptors.response.use(res =>{
  return res.data
  // return res
},err=>{
  console.log(err)

  if (err.__CANCEL__) {
    return Promise.reject({
      cancel: true
    })
  }

  if (!err || !err.response) {
    return Promise.reject(err)
  }

  const { msg, message, code } = err.response.data

  if (code === 301) {
    router.replace('/login')
    return Promise.reject(err)
  }
  let m = msg || message
  if (m) {
    Notify({ type: 'danger', message: m })
  } else {
    Notify({ type: 'danger', message: '服务器连接失败,请重试' })
  }
  return Promise.reject(err)
})

export default instance